import React, { useEffect, useState, useRef } from 'react'
import { Table, Button, Modal, Switch, } from 'antd';
import axios from 'axios';
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import UserForm from '../../../components/user-manage/UserForm';
const { confirm } = Modal;
export default function RightList() {
  const [dataSource, setdataSource] = useState([])

  //控制添加用户modal的显示状态
  const [isOpen, setisOpen] = useState(false)
  const [roleList, setroleList] = useState([])
  const [wholeRoleList, setwholeRoleList] = useState([])
  const [regionList, setregionList] = useState([])
  //控制更新操作modal的显示状态
  const [isUpdate, setisUpdate] = useState(false)
  const addForm = useRef(null)
  const updateForm = useRef(null)
  const [isUpdateDisabled, setisUpdateDisabled] = useState(false)
  //用于存储更新操作的item
  const [current, setcurrent] = useState(null)


  const {roleId,region,username} =JSON.parse(localStorage.getItem('token'))

  useEffect(() => {
    axios.get('/regions').then(res => {
      const list = res.data
      setregionList(list)
      // console.log(list, 'rigon');
    })
  }, [])

  useEffect(() => {
    axios.get('/roles').then(res => {
      const list = res.data
      //构造rolelis所需要的字段数组
      const obj = (value, label, id, rights) => {
        return {
          value,
          label,
          id,
          rights
        }
      }
      const rolesbuild = (list) => {
        let dataNew = [];    //新数组
        list.map(item => {
          return dataNew.push(obj(item.roleType, item.roleName, item.id, item.rights));
        });
        return dataNew
      }

      setroleList(rolesbuild(list))
      setwholeRoleList(list)
      // console.log(list,'role');
      // console.log(roles(list));

    })
  }, [])
  



  


  useEffect(() => {
    const roleObj ={
      '1':'superadmin',
      '2':'admin',
      '3':'editor'
    }
    axios.get('/users?_expand=role').then(res => {
      const list = res.data
      setdataSource(roleObj[roleId]==='superadmin'?list:[
        ...list.filter(item=>item.username===username),
        ...list.filter(item=>item.region===region&& roleObj[item.roleId]==='editor')
      ])
    })
  }, [])


  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      filters:[
        ...regionList.map(item=>({
          text:item.title,
          value:item.value
        })),
        {
          text:'全球',
          value:''
        }
      ],
      onFilter:(value,item)=>item.region===value,
      

      render: (region) => {
        return <b>{region === '' ? '全球' : region}</b>
      }
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render: (role) => {
        return role?.roleName
      }
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '用户状态',
      dataIndex: 'roleState',
      render: (roleState, item) => {
        return <Switch checked={roleState} disabled={item.default} onChange={() => handleChange(item)}></Switch>
      }
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Button type="danger" shape="circle" icon={<DeleteOutlined />} onClick={() => showDeleteConfirm(item)} disabled={item.default} />

          <Button type="primary" shape="circle" icon={<EditOutlined />} disabled={item.default} onClick={() => handleUpdate(item)} />
        </div>
      }
    }
  ];


  // 编辑状态

   const handleUpdate= (item)=>{
   setTimeout(()=>{
     updateForm.current.setFieldsValue(item)
     if(item.roleId===1){
      //禁用
      setisUpdateDisabled(true)
     }else{
      //取消禁用
      setisUpdateDisabled(false)
     }
   },1)
   setisUpdate(true)


    //存储item 给更新成功后的操作使用
    setcurrent(item)
  }



  //开关改变状态
  const handleChange = (item) => {
    // console.log(item);

    //在页面同步
    item.roleState = !item.roleState
    setdataSource([...dataSource])
    //在后端同步
    axios.patch(`/users/${item.id}`, {
      roleState: item.roleState
    })
  }




  //删除
  const showDeleteConfirm = (item) => {
    confirm({
      title: '你确定要删除吗？',
      icon: <ExclamationCircleOutlined />,
      // content: 'Some descriptions',
      okText: 'Yes',
      okType: 'danger',
      cancelText: 'No',
      onOk() {
        // console.log('OK');
        deleteMethod(item)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  //删除方法
  const deleteMethod = (item) => {
    setdataSource(dataSource.filter(data => data.id !== item.id))
    axios.delete(`/users/${item.id}`)
  }

  //添加用户
  const addFormOK = () => {
    // console.log('add',addForm);
    //校验表单
    addForm.current.validateFields().then(value => {
      setisOpen(false)

      //点击确定后重置表单
      addForm.current.resetFields()
      //post到后端，生成id，在设置dataSource，方便以后的删除和更新
      axios.post(`/users`, {
        ...value,
        'roleState': true,
        'default': false
      }).then(res => {
        console.log(res.data);
        console.log(value.roleId);
        setdataSource([...dataSource, {
          ...res.data,
          role: wholeRoleList.filter(item => item.id === value.roleId)[0]
          //解决要刷新才能显示roleId的问题
        }])
      })
    }).catch(err => {
      console.log(err);
    })
  }
  

  //更新操作
  const updateFormOK = () => {
    
    updateForm.current.validateFields().then(value=>{
      // console.log(value);
      setisUpdate(false)
     
       setdataSource(dataSource.map(item=>{
        if(item.id===current.id){
          return{
            ...item,
            ...value,
            role: wholeRoleList.filter(data => data.id === value.roleId)[0]
          }
        }
        return item
       }))
       setisUpdateDisabled(!isUpdateDisabled)

       //同步后端

       axios.patch(`/users/${current.id}`,
       value)
     })
  }



  return (
    <div>
      <Button type='primary' onClick={() => {
        setisOpen(true)
      }}>添加用户</Button>
      <Table dataSource={dataSource} columns={columns} pagination={{
        pageSize: 5
      }} rowKey={item => item.id} />;


      <Modal
        open={isOpen}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setisOpen(false)
        }}
        onOk={() => addFormOK()
        }
      >
        <UserForm regionList={regionList} roleList={roleList} ref={addForm}></UserForm>
      </Modal>


      <Modal
        open={isUpdate}
        title="更新用户"
        okText="更新"
        cancelText="取消"
        onCancel={() => {
          setisUpdate(false)
          setisUpdateDisabled(!isUpdateDisabled)
        }}
        onOk={() => updateFormOK()
        }
      >
        <UserForm regionList={regionList} roleList={roleList} ref={updateForm} isUpdateDisabled={isUpdateDisabled} isUpdate={true}></UserForm>
      </Modal>

    </div>
  )
}
